<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <r-table
      :tableHandles="tableHandles"
      :isSelection="true"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @select="selectCall"
      @refresh="init()"
    ></r-table>
    <!--    <r-form :formRules="formRules" :formHandle="formHandle" :formData="formData" :formCols="formCols" ref="elForm" labelWidth="200px" dialogWidth="1000px" :isHandle="true" />-->

    <r-form
      labelWidth="150px"
      :isHandle="true"
      :formRules="formRules2"
      :formCols="formCols2"
      :formHandle="formHandle2"
      :formData="formData2"
      ref="elForm2"
      :inline="false"
      dialogWidth="850px"
    >
      <div slot="slot3">
        <div
          id="searchResultPanel"
          style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"
        ></div>
        <p>
          点击地图拾取坐标 经度：{{ formData2.lng }} 纬度：{{ formData2.lat }}
        </p>
        <div id="l-map"></div>
      </div>
    </r-form>

    <!--    <add_device v-if="add_device_data.show" v-on:add_device_call="add_device_call"></add_device>-->
    <!--    <warehouse_gate :res="warehouse_gate_data" v-if="warehouse_gate_data.show" v-on:warehouse_gate_dall="warehouse_gate_dall"></warehouse_gate>-->
    <related_packages ref="related_packages"></related_packages>
  </div>
</template>
<script>
// import add_device from "./cus/add_device";
// import warehouse_gate from "./cus/warehouse_gate";
import related_packages from "./cus/related_packages";
import baidumap from "../js/baidumap";
export default {
  components: {
    // add_device,
    // warehouse_gate,
    related_packages
  },
  data() {
    return {
      baiduMap: null,
      add_device_data: {
        show: false
      },
      warehouse_gate_data: {
        id: "",
        show: false
      },
      searchData: {
        deviceName: "",
        sn: "",
        deviceStatus: "",
        operatorId: "",
        agentId: "",
        distStatus: "",
        commonType: "",
        deviceType: 2
      },
      searchForm: [
        {
          type: "input",
          prop: "sn",
          placeholder: "Device Number",
          width: 150
        },
        {
          type: "input",
          prop: "deviceName",
          placeholder: "Device Name",
          width: 150
        },
        {
          type: "select",
          prop: "operatorId",
          placeholder: "所属Operator",
          width: 150
        },
        {
          type: "select",
          prop: "agentId",
          placeholder: "Belonging Agent商",
          width: 150
        },
        {
          type: "select",
          prop: "distStatus",
          placeholder: "是否分配",
          width: 150,
          options: [
            { label: "未分发", value: "0" },
            { label: "已分发", value: "1" }
          ]
        },
        {
          type: "select",
          prop: "commonType",
          placeholder: "PublicType",
          width: 150,
          options: [
            { label: "Public", value: "1" },
            { label: "Private", value: "2" }
          ]
        }
        // {
        //   type: 'select',
        //   prop: 'name',
        //   placeholder: '设备Type',
        //   width: 150,
        //   options:[
        //     {label:'换电柜',value:'1'},
        //     {label:'租车',value:'2'},
        //     {label:'Charging Cabinet',value:'3'},
        //   ]
        // },
      ],
      searchHandle: [
        {
          label: "Search",
          type: "success",
          icon: "el-icon-search",
          handle: e => this.init()
        }
      ],

      tableHandles: [
        // {
        //   label: "关联广告合集",
        //   type: "primary",
        //   handle: e => this.elFormVisible()
        // },
        {
          label: "关联Package",
          type: "primary",
          handle: e => {
            if (this.deviceId.length == 0) {
              return this.$message({
                message: "Please Select设备！",
                type: "error"
              });
            }
            this.$refs.related_packages.showFun(this.deviceId);
          }
        },
        {
          label: "Add设备",
          type: "primary",
          handle: e => {
            this.add();
          }
        }
        // {
        //   label: "DownloadTemplate",
        //   type: "primary",
        //   handle:async () => {
        //     const res=await this.apis.importTemplate();
        //
        //     location.href=process.env.VUE_APP_URL+res.msg;
        //
        //   }
        // }
      ],
      tableData: [],
      tableCols: [
        {
          label: "Device Number",
          prop: "sn"
        },
        {
          label: "QR Code",
          type: "image",
          width: 100,
          prop: "qrCode"
        },
        {
          label: "Device Name",
          prop: "deviceName"
        },
        {
          label: "铺设站点",
          prop: "siteId"
        },
        {
          label: "Current定位",
          prop: "lng",
          formatter: row => {
            if (row.lng) {
              return row.lng + "," + row.lat;
            } else {
              return "-";
            }
          }
        },
        /* {
          label: 'Charging CabinetPackage',
          prop: 'mealId'
        }, */
        {
          label: "设备所属",
          prop: "operatorName"
        },
        {
          label: "Maintenance Personnel",
          prop: "merName"
        },
        // {
        //   label: '广告合集',
        //   prop: 'giftMoney'
        // },
        {
          label: "电量表",
          prop: "usedElectric"
        },
        {
          label: "设备Status",
          prop: "deviceStatus",
          formatter: e => {
            if (e.deviceStatus == 1) {
              return "(Online)运行中";
            } else if (e.deviceStatus == 2) {
              return "Offline";
            } else if (e.deviceStatus == 3) {
              return "设备故障";
            } else if (e.deviceStatus == 0) {
              return "-";
            }
          }
        },
        /* {
          label: 'Update Time',
          prop: 'lastTime'
        }, */
        {
          label: "EnableStatus",
          type: "switch",
          prop: "useStatus",
          values: [1, 2],
          change: row => this.changestate(row)
        },
        {
          label: "Operations",
          type: "button",
          width: 300,
          btnList: [
            {
              label: "Edit",
              type: "text",
              handle: row => {
                this.add(row);
              }
            },
            {
              label: "Delete",
              type: "text",
              handle: async row => {
                this.$confirm("确定要Delete吗?", "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(async () => {
                    var res = await this.apis.device_del({
                      id: row.id
                    });
                    this.$message({
                      type: "success",
                      message: "DeleteSuccess!"
                    });
                    this.init();
                  })
                  .catch(() => {});
              }
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      // formData: {
      //   name: "",
      //   money: "",
      //   giftMoney: "",
      //   status: ""
      // },
      // formCols: [
      //   { type: "input", label: "Package Name", width: 350, prop: "name" },
      //   { type: "input", label: "PackageMoney", width: 350, prop: "money", remark: '元' },
      //   { type: "input", label: "Gift Amount", width: 350, prop: "giftMoney", remark: '元' },
      //   { type: "switch", label: "上线/下线", width: 350, prop: "status" },
      // ],
      // formRules: {
      //   name: [
      //     { required: true, message: 'Please InputPackage Name', trigger: 'blur' },
      //   ],
      //   money: [
      //     { required: true, message: 'Please InputPackageMoney', trigger: 'blur' },
      //   ],
      //   giftMoney: [
      //     { required: true, message: 'Please InputPackageMoney', trigger: 'blur' },
      //   ],
      // },
      // formHandle: [
      //   {
      //     label: "Cancel",
      //     handle: e => this.elFormVisible(),
      //   },
      //   {
      //     label: "Confirm",
      //     type: "success",
      //     handle: e => this.elFormSubmit(),
      //   },
      //
      // ],

      formData2: {
        deviceNo: "",
        deviceName: "",
        address: "",
        siteId: "",
        lng: "",
        lat: "",
        operatorId: "",
        agentId: "",
        merId: "",
        boxNum: "",
        sim: "",
        deviceType: "2",
        mealId: "",
        carDeposit: "",
        btType: ""
      },
      formCols2: [
        {
          type: "input",
          label: "Device Number",
          placeholder: "Please Enter",
          width: 350,
          prop: "deviceNo"
        },
        {
          type: "input",
          label: "Device Name",
          placeholder: "Please Enter",
          width: 350,
          prop: "deviceName"
        },
        {
          type: "select",
          label: "BatteryType",
          placeholder: "Please Enter",
          width: 350,
          prop: "btType",
          options: [
            { label: "48V", value: 48 },
            { label: "60V", value: 60 },
            { label: "72V", value: 72 }
          ]
        },
        // { type: "input", label: "格子数量", placeholder: 'Please Enter', width: 350, prop: "boxNum", },
        // { type: "input", label: "sim 编号", placeholder: 'Please Enter', width: 350, prop: "sim", },
        // { type: "select", label: "设备Type", placeholder: 'Please Enter', width: 350, prop: "deviceType",options:[
        //     {label:'换电柜',value:'1'},
        //     {label:'租车',value:'2'},
        //     {label:'Charging Cabinet',value:'3'},
        //   ] },
        {
          type: "select",
          label: "选择站点",
          placeholder: "Please Enter",
          width: 350,
          prop: "siteId",
          options: []
        },
        {
          type: "select",
          label: "选择Operator",
          placeholder: "Please Enter",
          width: 350,
          prop: "operatorId",
          options: []
        },
        {
          type: "select",
          label: "选择Agent",
          placeholder: "Please Enter",
          width: 350,
          prop: "agentId",
          options: []
        },
        {
          type: "select",
          label: "Select Maintenance",
          placeholder: "Please Enter",
          width: 350,
          prop: "merId",
          options: []
        },
        {
          type: "input",
          label: "车辆Deposit",
          placeholder: "Please Enter",
          width: 350,
          prop: "carDeposit",
          remark: "元"
        }
        // { type: "select", label: "关联Package",placeholder:'Please Enter', width: 350, prop: "mealId" },
        // { type: "input", id: 'suggestId', label: "站点地址", width: 350, prop: "address" },
        // { type: "slot", name: 'slot3', label: '', prop: "lng" },
      ],
      formRules2: {
        deviceNo: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        btType: [{ required: true, message: "Please Select", trigger: "blur" }],
        boxNum: [{ required: true, message: "Please Enter", trigger: "blur" }],
        sim: [{ required: true, message: "Please Enter", trigger: "blur" }],
        deviceType: [
          { required: true, message: "Please Select", trigger: "blur" }
        ],
        siteId: [{ required: true, message: "Please Select", trigger: "blur" }],
        operatorId: [
          { required: true, message: "Please Select", trigger: "blur" }
        ],
        agentId: [
          { required: true, message: "Please Select", trigger: "blur" }
        ],
        merId: [{ required: true, message: "Please Select", trigger: "blur" }],
        lng: [
          { required: true, message: "请点击地图选择经纬度", trigger: "blur" }
        ],
        address: [
          { required: true, message: "Please Input详细地址", trigger: "blur" }
        ],
        carDeposit: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ]
      },
      formHandle2: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible("", "elForm2")
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ],

      deviceId: []
    };
  },
  computed: {},
  mounted() {
    this.init();
    this.site_list();
    this.operator_list();
    this.agent_list();
    this.maintenancer_list();
    this.mealExchange_list();
  },
  methods: {
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.device_list(parm);
      if (res) {
        this.tableData = res.rows;
        this.tablePage.total = res.total;
      }
    },
    async elFormSubmit() {
      this.$refs.elForm2.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData2.id) {
            let res = await this.apis.device_updata(this.formData2);
            if (res) {
              this.init();
              this.elFormVisible("", "elForm2");
            }
          } else {
            let res = await this.apis.device_save(this.formData2);
            if (res) {
              this.init();
              this.elFormVisible("", "elForm2");
            }
          }
        }
      });
    },
    async changestate(row) {
      let res = await this.apis.device_updata({
        id: row.id,
        useStatus: row.useStatus
      });

      this.$message({
        message: "OperationsSuccess！",
        type: "success"
      });
    },
    elFormDetail(row) {
      console.log(row);
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });

      this.formData.status = row["state"] == 1 ? true : false;
      this.formData.id = row.id;
      // if (this.formCols[1].label == '登录密码') {
      //     this.formCols.splice(1, 1)
      // }

      this.elFormVisible();
    },
    map() {
      var that = this;
      var map = baidumap(that);
      this.baiduMap = map;
      var geoc = new BMap.Geocoder();
      map.addEventListener("click", function(e) {
        that.formData2.lng = e.point.lng;
        that.formData2.lat = e.point.lat;
        var pt = e.point;
        geoc.getLocation(pt, function(rs) {
          var addComp = rs.addressComponents;
          that.formData.city = addComp.city;
          // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
        });
      });
      map.enableScrollWheelZoom(); //Enable滚轮放大缩小，默认Forbidden
      map.enableContinuousZoom(); //Enable地图惯性拖拽，默认Forbidden
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 10);
      });
    },
    add(row) {
      if (row) {
        this.formData2.id = row.id;
      } else {
        this.formData2.id = "";
      }
      this.elFormVisible("", "elForm2").then(res => {
        if (row) {
          Object.keys(this.formData2).forEach(key => {
            this.formData2[key] = row[key];
          });
        }
      });
    },
    //站点列表
    async site_list() {
      const res = await this.apis.site_list({
        pageNum: 1,
        pageSize: 100000
      });

      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });

      this.formCols2[
        this.labIndex2(this.formCols2, "siteId")
      ].options = options;
    },

    //Operator-列表
    async operator_list() {
      const res = await this.apis.operator_list({
        pageNum: 1,
        pageSize: 100000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });

      this.formCols2[
        this.labIndex2(this.formCols2, "operatorId")
      ].options = options;
    },
    //Agent列表
    async agent_list() {
      const res = await this.apis.agent_list({
        pageNum: 1,
        pageSize: 100000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });

      this.formCols2[
        this.labIndex2(this.formCols2, "agentId")
      ].options = options;
    },
    //Maintenance Personnel List
    async maintenancer_list() {
      const res = await this.apis.maintenancer_list({
        pageNum: 1,
        pageSize: 1000000,
        status: 1
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.userName,
          value: res.id
        });
      });

      this.formCols2[this.labIndex2(this.formCols2, "merId")].options = options;
    },

    //Package列表
    async mealExchange_list() {
      const res = await this.apis.mealExchange_list({
        pageNum: 1,
        pageSize: 1000000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.mealName,
          value: res.id
        });
      });
      // this.formCols2[this.labIndex2(this.formCols2, 'mealId')].options = options;
    },
    // warehouse_gate_dall(){
    //   this.warehouse_gate_data.show=false;
    // },
    selectCall(rows) {
      console.log(rows);
      this.deviceId = [];
      let deviceId = [];
      rows.map(res => {
        deviceId.push(res.id);
      });
      this.deviceId = deviceId;
    }
  }
};
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 10px;
}
.Tip {
  margin-left: 20px;
}

#l-map {
  height: 250px;
  width: 100%;
}
#r-result {
  width: 100%;
}
</style>
